package com.banciyuan.bcywebview.biz.groupdetail;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.recycleview.OnRecyclerItemClickListener;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.circles.decoration.ItemOffsetDecoration;
import com.banciyuan.bcywebview.biz.detail.atperson.AtPersonActivity;
import com.banciyuan.bcywebview.biz.detail.EditActivity;
import com.banciyuan.bcywebview.biz.post.uploadpic.UploadAsyncHelper;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderLoaderInter;
import com.banciyuan.bcywebview.biz.post.uploadpic.receiver.UploaderReceiver;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.PhotoActivity;
import com.banciyuan.bcywebview.biz.write.write.WriteHelper;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.encrypt.MD5;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Multi;

/**
 * Created by squall on 2015/8/24.
 */
public class AddGroupActivity extends BaseActivity implements View.OnClickListener, ActionbarHelper.OnActionCallbacks {

    private static final int GO_NEXT = 54;

    private boolean SAVE_FALG = false;
    private boolean click_flag = false;

    private EditText title_et;
    private EditText content_et;
    private TextView title_num_tv;

    private ImageView ivAt;
    private ImageView img_iv;
    private TextView tv_save;

    private RecyclerView recyclerView;
    private HeaderHolder headerHolder;

    private MyProgressDialog mDialog;
    private AddGroupAdapter mAdapter;
    private RequestQueue queue;
    private String title = "";
    private String defaultTag = "";
    private String defaultWork = "";

    private List<PhotoModel> plist = new ArrayList<>();
    private Map<String, String> pathList = new HashMap<>();
    private ItemTouchHelper itemTouchHelper;

    private UploaderReceiver uploaderReceiver;
    private UploadAsyncHelper uploadPicHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_group);
        registerBroadCast();
        initArgs();
        initActionbar();
        initProgressbar();
        initUi();
        initAction();
        initDrag();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(uploaderReceiver);
    }

    private void registerBroadCast() {
        uploaderReceiver = new UploaderReceiver(new UploaderLoaderInter() {
            @Override
            public void onProgress(double progress, String key) {
                for (PhotoModel p : plist) {
                    String tempPath = ImageManager.getTemp(AddGroupActivity.this) + MD5.getMD5(p.getOriginalPath());
                    if (tempPath.equals(key)) {
                        p.setProgress(progress);
                        mAdapter.notifyItemChanged(plist.indexOf(p) + 1);
                    }
                }
            }

            @Override
            public void onFinish(Multi m) {
                if (m.isUpdate_status()) {
                    pathList.put(m.getLocal_path(), m.getPath());
                }
                for (PhotoModel p : plist) {
                    String tempPath = ImageManager.getTemp(AddGroupActivity.this) + MD5.getMD5(p.getOriginalPath());
                    if (tempPath.equals(m.getLocal_path())) {
                        p.setIsUpload(true);
                        mAdapter.notifyItemChanged(plist.indexOf(p) + 1);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFail() {

            }
        });
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UploaderLoaderInter.PROGRESS_KEY);
        intentFilter.addAction(UploaderLoaderInter.UPLOAD_FINISH_KEY);
        registerReceiver(uploaderReceiver, intentFilter);
    }

    @Override
    protected void initArgs() {
        Intent intent = getIntent();
        if (null != intent) {
            if (!TextUtils.isEmpty(intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE))) {
                title = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
            }
            defaultWork = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
            defaultTag = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        }
        queue = VolleyQueue.getRquest(this);
        uploadPicHelper = new UploadAsyncHelper(this, true);
    }

    private void initDrag() {
        itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                int dragFlags = 0;
                int swipeFlags = 0;
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                } else {
                    dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                }
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                if (fromPosition == 0 || fromPosition - 1 >= plist.size() || toPosition == 0 || toPosition - 1 >= plist.size())
                    return false;
                if (fromPosition < toPosition) {
                    for (int i = fromPosition - 1; i < toPosition - 1; i++) {
                        Collections.swap(plist, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition - 1; i > toPosition - 1; i--) {
                        Collections.swap(plist, i, i - 1);
                    }
                }
                mAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE && viewHolder != null) {
                    viewHolder.itemView.setAlpha(0.8f);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                if (viewHolder != null) {
                    viewHolder.itemView.setAlpha(1f);
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }

        });
        itemTouchHelper.attachToRecyclerView(recyclerView);
        recyclerView.addOnItemTouchListener(new OnRecyclerItemClickListener(recyclerView, new OnRecyclerItemClickListener.ItemTouchHelperGestureListener() {
            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                int fromPosition = vh.getAdapterPosition();
                if (fromPosition > 0 && fromPosition - 1 < plist.size()) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        }));
    }

    @Override
    protected void initAction() {
        title_et.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                showLength(editable.toString().length());

            }
        });

        content_et.addTextChangedListener(new TextWatcher() {

            String preStr = "";
            String nowStr = "";

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                nowStr = s.toString();
                if ((nowStr.length() - preStr.length()) == 1) {
                    char lastChar = s.charAt(s.length() - 1);
                    if ('@' == lastChar) {
                        Intent intent = new Intent(AddGroupActivity.this, AtPersonActivity.class);
                        startActivityForResult(intent, EditActivity.GOATPERSON);
                    }
                }
                preStr = nowStr;
            }
        });

        tv_save.setOnClickListener(this);
        img_iv.setOnClickListener(this);
        ivAt.setOnClickListener(this);
    }

    private void showLength(int length) {

        if (length > 0) {
            tv_save.setTextColor(getResources().getColorStateList(R.color.pink));
            SAVE_FALG = true;
        } else {
            tv_save.setTextColor(getResources().getColorStateList(R.color.font_color));
            SAVE_FALG = false;
        }

        if (length >= 20) {
            title_num_tv.setVisibility(View.VISIBLE);
            if (length > 30) {
                title_num_tv.setTextColor(getResources().getColorStateList(R.color.darkred));
                tv_save.setTextColor(getResources().getColorStateList(R.color.font_color));
                SAVE_FALG = false;
            } else {
                title_num_tv.setTextColor(getResources().getColorStateList(R.color.line));
            }
            title_num_tv.setText(String.valueOf(Math.abs(length - 30)));
        } else {
            title_num_tv.setVisibility(View.GONE);
        }
    }

    public class HeaderHolder extends RecyclerView.ViewHolder {

        public HeaderHolder(View itemView) {
            super(itemView);
            title_et = (EditText) itemView.findViewById(R.id.group_add_title);
            content_et = (EditText) itemView.findViewById(R.id.group_add_content);
            title_num_tv = (TextView) itemView.findViewById(R.id.group_add_text);
        }
    }

    @Override
    protected void initUi() {
        recyclerView = (RecyclerView) findViewById(R.id.recycleview);
        img_iv = (ImageView) findViewById(R.id.group_add_img);
        ivAt = (ImageView) findViewById(R.id.at_add_img);
        headerHolder = new HeaderHolder(LayoutInflater.from(this).inflate(R.layout.add_group_header, null));
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return position == 0 ? 3 : 1;
            }
        });
        recyclerView.addItemDecoration(new ItemOffsetDecoration(UIUtils.dip2px(8, this)));
        recyclerView.setLayoutManager(gridLayoutManager);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        mAdapter = new AddGroupAdapter(plist, this, headerHolder);
        recyclerView.setAdapter(mAdapter);

        tv_save.setTextColor(getResources().getColorStateList(R.color.font_color));
        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        onCancelClick = new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
            }
        };
        title_et.setText(title);
        showLength(title.length());
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();

        title_et.requestFocus();
    }

    @Override
    protected void initActionbar() {
        View mActionBarView = findViewById(R.id.base_action_bar);
        ActionbarHelper mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.send_topic));
        mActionbarHelper.addItemOneText(getString(R.string.next), getResources().getColor(R.color.font_color));
        mActionbarHelper.addBackText(getString(R.string.mydialog_cancel));
        mActionbarHelper.setActionCallbacks(this);
        tv_save = (TextView) findViewById(R.id.base_action_bar_home_text_item);
    }

    private void changeSelectImg(List<PhotoModel> templist) {
        plist.clear();
        plist.addAll(templist);

        if (null == mAdapter) {
            mAdapter = new AddGroupAdapter(plist, this, headerHolder);
            recyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
        beginUpload();
    }

    private void beginUpload() {
        List<PhotoModel> uploadList = new ArrayList<>();
        for (PhotoModel p : plist) {
            String tempPath = ImageManager.getTemp(AddGroupActivity.this) + MD5.getMD5(p.getOriginalPath());
            if (pathList.get(tempPath) == null) {
                uploadList.add(p);
            } else {
                p.setIsUpload(true);
                mAdapter.notifyItemChanged(plist.indexOf(p));
            }
        }
        uploadPicHelper.getToken("", "", GroupApi.getGetgroupuploader(), uploadList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != GO_NEXT) {
            if (resultCode != RESULT_OK) {
                return;
            }
            if (requestCode == WriteHelper.PICK_IMAGE) {
                List<PhotoModel> temp = (List<PhotoModel>) data.getExtras().getSerializable("photos");
                changeSelectImg(temp);
            } else if (requestCode == EditActivity.GOATPERSON) {
                String personname = data.getStringExtra("personname");
                content_et.setText(content_et.getText().toString() + personname);
                content_et.setSelection(content_et.getText().length());
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        } else {
            if (resultCode == 999) {
                finish();
            }
        }
    }

    private void verifyName() {
        click_flag = true;
        String url = HttpUtils.BASE_URL + GroupApi.getVerifyname();
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(AddGroupActivity.this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.NAME, title_et.getText().toString()));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, AddGroupActivity.this)) {
                    goEditGroup();
                }
                click_flag = false;
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                click_flag = false;
            }
        };
        HashMap<String, String> map = HttpUtils.getData(paramsList);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(stringRequestParam);
    }

    private void goEditGroup() {
        List<String> upload = new ArrayList<>();
        for (PhotoModel p : plist) {
            String tempPath = ImageManager.getTemp(AddGroupActivity.this) + MD5.getMD5(p.getOriginalPath());
            if (pathList.get(tempPath) != null) {
                upload.add(pathList.get(tempPath));
            }
        }
        if (upload.size() == plist.size()) {
            Intent intent = new Intent();
            intent.setClass(AddGroupActivity.this, EditGroupActivity.class);
            intent.putExtra("pathList", (Serializable) upload);
            intent.putExtra("name", title_et.getText().toString() == null ? "" : title_et.getText().toString());
            intent.putExtra("content", content_et.getText().toString() == null ? "" : content_et.getText().toString());
            intent.putExtra(gotoUtil.INTENT_VALUE_TWO, defaultWork);
            intent.putExtra(gotoUtil.INTENT_VALUE_THREE, defaultTag);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivityForResult(intent, GO_NEXT);
        } else {
            MyToast.show(this, getString(R.string.img_still_upload));
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.group_add_img:
                if (plist.size() < 9) {
                    startImagePic();
                } else {
                    MyToast.show(AddGroupActivity.this, getString(R.string.not_over_nine));
                }
                break;
            case R.id.base_action_bar_home_text_item:
                if (UserDataHelper.ifLogin(AddGroupActivity.this)) {
                    if (SAVE_FALG) {
                        if (!click_flag) {
                            verifyName();
                        }
                    }
                } else {
                    MyToast.show(AddGroupActivity.this, getString(R.string.login_first));
                    finish();
                }
                break;
            case R.id.at_add_img:
                content_et.setText(content_et.getText().toString() + "@");
                content_et.setSelection(content_et.getText().length());
                break;
        }
    }

    public void startImagePic() {
        Intent intent = new Intent(AddGroupActivity.this, PhotoActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("photos", (Serializable) plist);
        intent.putExtras(bundle);
        startActivityForResult(intent, WriteHelper.PICK_IMAGE);
    }


    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {

    }
}
